package cate.game.server.service;

import cate.game.GameBody;
import cp.solution.ops.status.SysOprStatus;
import cp.solution.pattern.Feedback;
import easy.java.struct.ref.IntRef;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class SystemService {

    @Resource
    UsefulCtx uc;

    public Feedback shutdown() {
        log.info("收到关闭游戏进程の请求");
        Feedback feedback = new Feedback().start();
        IntRef nShutdown = new IntRef();
        uc.games.getAllIncludeNotOpen().forEach(game -> {
            game.shutdown();
            nShutdown.v++;
        });
        feedback.text("已关闭"+nShutdown.v+"个游戏服");
        return feedback.stop();
    }

    public Feedback stopGame(int srvId) {
        log.info("收到关闭GameBodyの请求：{}", srvId);
        Feedback feedback = new Feedback().start();
        GameBody game = uc.getGame(srvId);
        game.shutdown();
        return feedback.text("已关闭游戏服("+srvId+")").stop();
    }

    public Feedback startGame(int srvId) throws Exception {
        Feedback feedback = new Feedback().start();
        GameBody game = uc.getGame(srvId);
        if(!game.isRunning()) {
            feedback.text("已启动游戏服("+srvId+")");
            game.restart();
        } else {
            feedback.text("游戏服("+srvId+")本来就在运行中");
        }
        return feedback.stop();
    }


    /** 获取系统操作状态 */
    public SysOprStatus loadSysOprStatus(int srvId) {
        GameBody game = uc.getGame(srvId);
        return game.loadSysOprStatus();
    }

    /** 被合服吞并前执行的结算行为 */
    public SysOprStatus mergeSettle(int srvId) {
        GameBody game = uc.getGame(srvId);
        SysOprStatus sos = game.handleMergeSettle();
        try {
            game.shutdown();
        } catch (Exception e) {
            log.error("", e);
        }
        return sos;
    }

    /** 游戏服数据清理 */
    public SysOprStatus cleanData(int srvId) {
        GameBody game = uc.getGame(srvId);
        return game.handleCleanData();
    }

}
